<?php
/**
 * Created by JetBrains PhpStorm.
 * User: cgp
 * Date: 13-4-6
 * Time: 上午12:03
 */
namespace pft\Prod;
use pft\Member\MemberAccount;
use \pft\Verify\Verify;
class ProductDev {
    const PRODUCT_WITH_TICKETS = true;
    const OPEN_DEBUG = true;
    const COUNT_TOTAL = 1;
    const NO_COUNT_TOTAL = 0;

    protected $db;
    protected $soap;
    protected $ErrArr = array('errcode'=>1003,'msg'=>'执行SQL语句失败,请联系网站管理员');
    protected $errMsg = array(
        1000 => '成功',
        1001 => '已存在相同名称的产品，添加失败',
        1002 => '终端数据写入失败',
        1003 => '执行SQL语句出错,请联系网站管理员',
        1004 => '记录不存在',
        1005 => '不能为空',
        1006 => '状态出错',
        1007 => '格式错误',
        1008 => '部分操作成功',
        1009 => '数据重复',
        1010 => '只能设置通过审核的产品状态',
    );

    /**
     * @param $db
     * @param null $soap
     */
    public function __construct($db, $soap=null)
    {
        $this->db = $db;
        $this->soap = $soap;
    }
    /**
     * 向终端写入数据
     *
     * @param string $title 产品名称
     * @param string $salerid 资源方6位数账号
     * @param int $mode 操作模式0写入1更新
     * @param string $src_title 所属产品名称
     * @param string $dlTxt 延迟验证
     * @return mixed
     */
    protected function _Write2Remote($title,$salerid,$mode=0,$src_title='', $dlTxt=NULL) {
        $s = \SoapInit::GetSoapInside();
        $title .= !empty($src_title) ? $src_title:'';
        if($mode==1) {
            return $s->Terminal_CFG_Update($title,$salerid,$dlTxt);
        }
        //echo  $salerid;
        $res = $s->Terminal_CFG($title,$salerid,$dlTxt);
        if(strpos($res,'|')!==false) {
            $t_no = explode('|', $res);
            return  array(
                'status' => 'ok',
                'msg'  => '生成终端号成功',
                'body' => $t_no[1]
            );
        }
        return array(
            'status' => 'fail',
            'msg'  => $res,
            'body' => ''
        );
    }

    /**
     * 删除软终端产品数据
     *
     * @param $salerIds
     * @return mixed
     */
    protected function _removeRemoteProd($salerIds) {
        $s = \SoapInit::GetSoapInside();
        return $s->clear_Terminal_CFG($salerIds);
    }

    /**
     * 根据相应字段验证产品是否已经存在
     *
     * @param string $pro 验证字段的值
     * @param string $colmn 字段名
     * @param array $other 字段名
     * @return mixed
     */
    protected function _chkProExist($pro, $colmn, $other=array())
    {
        $str = "SELECT COUNT(*) AS c FROM uu_land WHERE `{$colmn}`='{$pro}'";
//        echo $str;
        if(!empty($other) && is_array($other)) {
            $str .= " AND " . self::getValues($other);
        }
//        echo $str;
        $this->db->query($str);
        $this->db->fetch_assoc();
        return $this->db->f('c');
    }

    /**
     * 获取产品总表ID
     *
     * @param $id 门票ID
     * @param $debug
     * @return mixed
     */
    protected function _getPid($id, $debug=false) {
        $str = "SELECT pid FROM uu_jq_ticket WHERE id={$id} LIMIT 1";
        if($debug) {
            echo 'getPid=', $str,'<br/>';
        }
        $this->db->query($str);
        $this->db->fetch_assoc();
        return $this->db->f('pid');
    }

    /**
     * 获得sql语句使用的字段名和值
     *
     * @param $params
     * @return string
     */
    protected function getValues($params) {
        $str = '';
        foreach($params as $key=>$val) {
            if($key=='order_end' && $val==''){
                $str .= "`{$key}`=NULL,";
            }else{
                $str .= "`{$key}`='{$val}',";
            }
        }
        return rtrim($str,',');
    }

    /**
     * 设置门票推荐度
     *
     * @param $id
     * @param $value
     * @return int
     */
    public function SetProdSort($id,$value) {
        $up_id = is_array($id) ? implode(',',$id) : rtrim($id,',');
        $str = "UPDATE `uu_jq_ticket` SET `px`={$value} WHERE pid IN({$up_id})";
        //echo $str;
        if($this->db->query($str)) {
            return 1000;
        }
        return 1003;
    }

    /**
     * 添加产品
     *
     * @param array $params 字段名=>值（参考uu_land表）
     * @param MemberAccount $mem MemberAccount的实例
     * @param INT $parent_id 关系表(pft_member_relationship)中的parent_id
     * @return mixed
     */
    public function AddProduct($params, MemberAccount $mem, $parent_id=0, $dltxt=NULL)
    {
        $memParams = array(
            'dname'=>$params['title'],
            'dtype'=>2,//直接供应方
            'password'=>'b81b84c7961ac41a9e619458511a98d9',//md5(md5('uu654321'))
        );
        //生成直接供应商
        $reg_res = $mem->register($memParams, array());
        if($reg_res['status']=='ok') {
            $res_account = explode('|', $reg_res['body']);
            $params['salerid'] = $res_account[1];
            if(strlen($params['salerid'])>6) {
                return array('errcode'=>1001,'msg'=>'添加失败，商户ID超出长度！');
            }
            //建立直接供应商与供应商关系
            $rel_res = $mem->createRelationship($params['apply_did'],
                $reg_res['body'],1,1);
            //TODO:建立直接供应方与直接供应方平级关系
            if($parent_id>0) {
                $res_res_p = $mem->createRelationship($parent_id,
                    $reg_res['body'],1,2);
            }
            if($reg_res['status']!='ok'){
                return $rel_res;
            }
        }
        else {
            return $reg_res;
        }
        //检测是否存在相同的产品名称，若存在则将产品名称重命名
        $strChkTitle = "SELECT COUNT(*) AS c FROM uu_land WHERE title='{$params['title']}'";
        $this->db->query($strChkTitle);
        $this->db->fetch_assoc();
        $count = $this->db->f('c');
        $src_title = $count>0? '_' . ($count+1):'';

        $res = self::_Write2Remote($params['title'], $params['salerid'],0,$src_title,$dltxt);
        if($res['status']=='ok') {
            $params['terminal'] = $res['body'];
            $params['status'] = 1;
            $stradd = "INSERT INTO uu_land SET ";
            $stradd .= $this->getValues($params);
            if($this->db->query($stradd)) {
                $lastid =  _mysql_insert_id();
                if($_SESSION['dtype']==6) {
                    MemberAccount::StuffOptLog($_SESSION['memberID'], $_SESSION['sid'], "发布产品【{$params['title']}】,ID【{$lastid}】");
                }
                return array('status'=>'ok','msg'=>'添加成功','lastid'=>$lastid);
            }
            else {
                return $this->ErrArr;
            }
        }
        else {
            $this->RemoveSaler($params['salerid']);
            return array('status'=>'fail','msg'=>"终端数据写入失败，可能是由于存在相同的产品名称导致，请您更改产品名称试试吧！\n（错误代码：{$res}）");
        }
    }

    /**
     * 计算数组差集的自定义函数
     *  使用方法：
     *      array_diff_uassoc($arr_new, $arr_old, array($this, '_c'));
     *      在类中使用时第三个参数（回调函数）必须是数组形式！
     *
     * @param $a
     * @param $b
     * @return int
     */
    private function _c($a, $b) {
        if($a===$b) return 0;
        return ($a > $b)? 1:-1;
    }

    /**
     * array_intersect_ukey 用回调函数比较键名来计算数组的交集
     *
     * @param $key1
     * @param $key2
     * @return int
     */
    private function _key_compare_func($key1, $key2){
        if ($key1 == $key2)
            return 0;
        else if ($key1 > $key2)
            return 1;
        else
            return -1;
    }
    /**
     * 添加景区门票
     *
     * @param array $data 门票表(uu_jq_ticket)字段名=>值
     * @param bool $debug 是否打开调试
     * @return array
     */
    public function AddTickets($data, $debug=false) {
        //TODO-done:验证景区是否已经存在，不存在的禁止添加
        if(! self::_chkProExist($data['landid'], 'id','uu_land')) {
            //echo '2';
            return array('status'=>'fail','msg'=>'景区不存在，添加失败');
        }

        $str = "INSERT INTO `uu_jq_ticket` SET ";
        $str .= $this->getValues($data);
        if($debug) {
            echo 'AddTickets = ', $str ,"<br/>\n";
        }
        if($this->db->query($str)) {
            $lastid = _mysql_insert_id();
            if($_SESSION['dtype']==6) {
                MemberAccount::StuffOptLog($_SESSION['memberID'], $_SESSION['sid'], "添加票类【{$data['title']}】,ID【{$lastid}】");
            }
            $pid = self::_getPid($lastid, $debug);
            $arrReturn = array(
                'lastid'=>$lastid,
                'pid'=>$pid,
                'landid'=>$data['landid']
            );
            $arrReturn['errcode']=1000;
            //TODO::判定是否为同步产品
            $sql = "SELECT sync_id,sync_status FROM uu_land WHERE id={$data['landid']} LIMIT 1";
            $this->db->query($sql);
            $r = $this->db->fetch_assoc();
            if ( $r['sync_status']==1 && $r['sync_id'] ) {
                \Sync::Notify(array(
                    'action'    =>'create_ticket',
                    'sync_id'   => $r['sync_id'],
                    'lid'       => $data['landid'],
                    'tid'       => $lastid,
                    'mid'       => $data['apply_did'],
                ));
            }
            return $arrReturn;
        }
        return $this->ErrArr;
    }
    /**
     * 产品扩展表（uu_land_f）新增OR更新
     *
     * @param $params
     * @param int $id 表ID，大于0为更新
     * @param bool $debug 是否调试
     * @return int
     */
    public function ProductExt($params, $id=0, $debug = false) {
        $queryflag = false;
        if($id>0) {
            $str_s = "SELECT * FROM uu_land_f WHERE id={$id} LIMIT 1";
            $this->db->query($str_s);
            $row = $this->db->fetch_assoc();
            $cr = array_diff_uassoc($params , $row, array($this, '_c'));
            if(count($cr)) {
                $str = "UPDATE uu_land_f SET " . $this->getValues($cr) . " WHERE id={$id} LIMIT 1";
                $chg_old  = array_intersect_ukey( $row, $cr, array($this,'_key_compare_func'));
                $old_data = serialize($chg_old);
                $new_data = serialize($cr);
                //TODO::判定是否为同步产品
                $sql = "SELECT sync_id,apply_did,sync_status FROM uu_jq_ticket WHERE id={$params['tid']} LIMIT 1";
                $this->db->query($sql);
                $r = $this->db->fetch_assoc();

                if ($r['sync_id']>0 && $r['sync_status']==1) {
                    $chkRes = \Sync::AttrChk($GLOBALS['le'], 'uu_land_f', $id);
                    $dbArr = \Sync::GetMulDB();
                    if ($chkRes['status']=='ok') {
                        \Sync::LogSync('uu_land_f', $id, $r['sync_id'], $chg_old, $cr, $dbArr['trans_le']);
                        \Sync::Notify(array(
                            'mid' => $r['apply_did'],
                            'tid' => $id,
                            'action' => 'update_land_f',
                        ));
                    }
                    else {
                        $msg = '更新成功,同步失败,同步产品已被下架。失败原因:' . $chkRes['msg'] . '。';
                        $sqlDown = "SELECT pid FROM uu_jq_ticket WHERE id={$r['sync_id']} LIMIT 1";
                        $dbArr['trans_le']->query($sqlDown);
                        $dbArr['trans_le']->fetch_assoc();
                        $myPid = $dbArr['trans_le']->f('pid');
                        $sqlDown = "UPDATE uu_products SET apply_limit=3 WHERE id=$myPid LIMIT 1";
                        $dbArr['trans_le']->query($sqlDown);
                        \Sync::writeLog(\Sync::now() . "|先行平台同步产品下架,原因:{$chkRes['msg']},先行tid={$r['sync_id']}", \Sync::LOG_DIR . 'attr_conflict.log');
                    }
                }
                $oper = isset($_SESSION['uudid']) ? $_SESSION['uudid']:'';
                Verify::LogVerify($row['pid'], 0, $old_data, $new_data, $oper);
                $queryflag = true;
            }
        }
        else {
            $str = "INSERT INTO uu_land_f SET " . $this->getValues($params);
            $queryflag = true;
        }
        if($debug) {
            echo $str;
        }
        //echo $str;
        if( $queryflag ) {
            $this->db->query($str);
        }
        return 1;
    }

    /**
     * 获取产品信息扩展表数据
     *
     * @param int $tid 门票ID
     * @param int $pid 产品ID
     * @return string
     */
    public function GetProdcutExt($tid, $pid=0){
        if(!$tid && !$pid) {
            return 'tid或pid不能全部为空！';
        }
        $str = "SELECT id, lid, p_type, dhour, mdays, mhour, startplace,".
            " endplace, rdays, ass_station, series_model, tourist_info, ".
            "confirm_sms, manual_verify, v_mobile_support, v_ID_support,v_time_limit ".
            "FROM uu_land_f WHERE ";
        $str .=   $tid > 0 ? "tid=" . $tid : "pid=" . $pid;
        $this->db->query($str);
        return $this->db->fetch_assoc();
    }

    /**
     * 产品排序设置
     *
     * @param $num 排序值
     * @param $id  门票id
     * @return int
     */
    public function SetPx($num,$id) {
        $id = is_array($id) ? implode(',',$id) : $id;
        $str = "UPDATE uu_jq_ticket SET px={$num} WHERE id IN ($id)";
        if($this->db->query($str)) {
            return 1000;
        }
    }
    /**
     * 更新景区信息（uu_land表）
     *
     * @param array $params 字段名=>值
     * @param integer $id   表ID
     * @param string $dlTxt 延迟验证
     * @return array
     */
    public function UpdateScenery(Array $params,$id, $dlTxt=NULL) {
        //echo 'abc';
        //TODO-CGP 验证该产品名称是否已经存在
        if(!self::_chkProExist($id, 'id')) {
            return array('errcode'=>1004,'msg'=>'修改的数据不存在，请刷新页面后重试');
        }
        $clns = implode(',', array_keys($params));
        $str = "SELECT {$clns},sync_id,sync_status,salerid,apply_did FROM uu_land WHERE id={$id} LIMIT 1";
        //echo $str;
        $this->db->query($str);
        $result     = $this->db->fetch_assoc();
        $sync_id    = $result['sync_id'];
        $sync_status= $result['sync_status'];
        $apply_did   = $result['apply_did'];
        unset($result['sync_id']);
        unset($result['sync_status']);
        unset($result['apply_did']);
        $diff_array = array_diff_uassoc($params, $result,array($this,'_c'));//比较差集
        if(!count($diff_array)) {
            return array('errcode'=>1000,'msg'=>'更新成功','lastid'=>$id);
        }
        $str = "UPDATE uu_land SET " . $this->getValues($diff_array). " WHERE id={$id} LIMIT 1";
         //echo $str;
        //return;
        //更新终端
        if(isset($diff_array['title']) || $dlTxt!==NULL){
            $r2 = $this->_Write2Remote($params['title'], $result['salerid'], 1,'',$dlTxt);
            if($r2!==100) {
                return array('errcode'=>1100,'msg'=>'更新终端名称失败,请核对产品名称后重新保存。错误代码：'.$r2);
            }
        }
        if($this->db->query($str)) {
            //TODO::同步产品;uu_land表更新，只记录更新的字段，不记录值。
            if ( $sync_status==1 && $sync_id >0 ) {
                $dbArr = \Sync::GetMulDB();
                //冲突的属性，要下架
                if ($dlTxt!==NULL) {
                    $sqlTrans = "UPDATE uu_land SET status=2 WHERE id=$sync_id LIMIT 1";
                    $dbArr['trans_le']->query($sqlTrans);

                    $sqlTransPro = "UPDATE uu_products SET apply_limit=3 WHERE concate_id=$sync_id";
                    $dbArr['trans_le']->query($sqlTransPro);
                }
                else {
                    $diff_columns = implode(',', array_keys($diff_array));
                    \Sync::LogSync('uu_land', $id, $sync_id,
                        array('diff_columns'=>$diff_columns),
                        array('diff_columns'=>$diff_columns),
                        $dbArr['trans_le']
                    );
                    \Sync::Notify(array(
                        'action'=>'update_land',
                        'lid'   => $id,
                        'mid'   => $apply_did,
                    ));
                }
            }
            //更新线路起始地点
            if(isset($diff_array['runtime']) && $params['p_type']=='B'){
                $strChkLine = "SELECT COUNT(*) AS c FROM uu_land_f WHERE lid={$id} LIMIT 1";
               // echo $strChkLine;
                $this->db->query($strChkLine);
                $this->db->fetch_assoc();
                $exist = $this->db->f('c');
                if($exist){
                    $s_e = explode('|', $diff_array['runtime']);
                    $s = $s_e[0];
                    $e = $s_e[1];
                    $strUpdatePlace = "UPDATE uu_land_f SET startplace='{$s}',endplace='{$e}' WHERE lid={$id}";
                   // echo $strUpdatePlace;
                    $this->db->query($strUpdatePlace);
                }
            }
            return array('errcode'=>1000,'msg'=>'更新成功','lastid'=>$id);
        }
        return $this->ErrArr;
    }
    /**
     * 更新产品
     * update：
     * 1.更新时间选择后提交无法修改的bug——2013年4月22日23:16:28
     * 2.只更新改变的字段——2013年4月22日23:16:28
     *
     * @param $params
     * @param $id
     * @return mixed
     */
    public function UpdateTicket($params,$id) {
        //TODO-CGP 验证该产品名称是否已经存在
        $vals = '';
        $str = <<<SQL
SELECT `id`, `landid`,`pid`, `title`, `tprice`, `uprice`, `px`,`status`, `pay`,
`notes`,`getaddr`, `ifs`, `delaydays`, `storage`, `s_limit_up`, `s_limit_low`,
`buy_limit_up`, `buy_limit_low`, `open_time`, `end_time`, `apply_did`,
`modify_op`, `order_limit`, `order_end`, `delaytype`,`sync_id`,`sync_status`
FROM uu_jq_ticket WHERE id={$id} LIMIT 1
SQL;


        $this->db->query($str);
        $result = $this->db->fetch_assoc();
        if(!$result) {
            return array('errcode'=>1004,'msg'=>'修改的数据不存在，请刷新页面后重试');
        }
        $chg_old = array();
        $chg_new = array();
        $chg_count = 0;

        foreach($params as $key=>$val) {
            if($key=='open_time' || $key=='end_time') {
                $result[$key] = substr($result[$key],0,10);
            }
            if($params[$key]!=$result[$key]) {
                if($key=='order_end' && $val==''){
                    $vals .= "`{$key}`=NULL,";
                }else{
                    $vals .= "`{$key}`='{$val}',";
                }
                $chg_count += 1;
                $chg_old[$key] = $result[$key];
                $chg_new[$key] = $params[$key];
            }
            else {
                unset($params[$key]);
            }
        }
        if(!strlen($vals)) {
            return array(
                'errcode'=>1000,
                'msg'=>'保存成功',
                'lastid'=>$id,
                'pid'=>$result['pid'],
                'affect_rows'=>$chg_count,
                'sync_status'=>$result['sync_status'],
                'sync_id'=>$result['sync_id'],
            );

        }

        $str = "UPDATE uu_jq_ticket SET ";
        $str .= rtrim($vals,',');
        $str .= " WHERE id={$id} LIMIT 1";

//        echo $str;
        //return;
        if($this->db->query($str)) {
            //修改记录
            $old_data = serialize($chg_old);
            $new_data = serialize($chg_new);
            $oper = isset($_SESSION['uudid']) ? $_SESSION['uudid']:'';
            Verify::LogVerify($result['pid'], $result['apply_did'],
                $old_data, $new_data, $oper);
            //TODO::判定是否为同步产品
            if ($result['sync_id'] && $result['sync_status']==1) {
                //检测是否有属性冲突
                $chkRes = \Sync::AttrChk($GLOBALS['le'], 'uu_jq_ticket', $id);
                $dbArr = \Sync::GetMulDB();
                if ($chkRes['status']=='ok') {
                    \Sync::LogSync('uu_jq_ticket', $id, $result['sync_id'], $chg_old, $chg_new,$dbArr['trans_le']);
                    \Sync::Notify(array(
                        'action'=>'update_ticket',
                        'tid'   => $id,
                        'mid'   => $result['apply_did'],
                    ));
                }
                else {
                    $msg = '更新成功,同步失败,同步产品已被下架。失败原因:' . $chkRes['msg'] . '。';
                    $sqlDown = "SELECT pid FROM uu_jq_ticket WHERE id={$result['sync_id']} LIMIT 1";
                    $dbArr['trans_le']->query($sqlDown);
                    $dbArr['trans_le']->fetch_assoc();
                    $myPid = $dbArr['trans_le']->f('pid');
                    $sqlDown = "UPDATE uu_products SET apply_limit=3 WHERE id=$myPid LIMIT 1";
                    $dbArr['trans_le']->query($sqlDown);
                    \Sync::writeLog(\Sync::now() . "|先行平台同步产品下架,原因:{$chkRes['msg']},先行tid={$result['sync_id']}", \Sync::LOG_DIR . 'attr_conflict.log');
                }

            }
            return array(
                'errcode'   =>1000,
                'msg'       => isset($msg) ? $msg : '更新成功',
                'lastid'    =>$id,
                'pid'       =>$result['pid'],
                'affect_rows'=>$chg_count,
                'sync_status'=>$result['sync_status'],
                'sync_id'    =>$result['sync_id'],
            );
        }
        return $this->ErrArr;
    }
    /**
     * 更新商品总表状态
     *
     * @param $status
     * @param $al
     * @param $pid
     */
    public function UpdateSuperProduct($status, $al, $pid) {
        $str = "UPDATE uu_products SET p_status={$status},apply_limit=$al WHERE id={$pid} LIMIT 1";
//        echo $str;
        return $this->db->query($str);
    }

    /**
     * 删除产品（删除产品都只有软删除）
     *
     * @param $id   产品表id(uu_products)
     * @return mixed
     */
    public function RemoveProduct($id) {
        $str = "UPDATE uu_products SET p_status=6 WHERE id IN ({$id})";
        //echo $str;
        if( $this->db->query($str) ) {
            return array('errcode'=>1000,'msg'=>'删除成功','removeId'=>$id);
        }
        return $this->ErrArr;
    }

    /**
     * 票类上下架、审核操作
     *
     * @param int $status 0未审核1正常2下架3被拒绝
     * @param $ids
     * @param $operid
     * @return array
     */
    public function SetTicketStatus($status, $ids, $operid)
    {
        $status = abs($status);
        if( is_array($ids) ) {
            $ids = implode(',',$ids);
        }
        else {
            $ids = rtrim($ids,',');
        }
        if($status==6) {
            $p_s = ',`p_status`=6';
        }
        elseif($status==1) {
            $str_chk_s = <<<SQL
            SELECT l.status,t.id as tid FROM uu_jq_ticket t left join uu_land l
            ON l.id=t.landid WHERE t.pid IN({$ids})
SQL;
            $this->db->query($str_chk_s);
            $cl = 0;
            while($r=$this->db->fetch_assoc()) {
                if($r['status']!=1) {
                    $cl = 1;
                    break;
                }
            }
            if($cl) {
                return array(
                    'status'=>'fail',
                    'msg'=>'请先将产品上架后再上架票类',
                    'body'=>''
                );
            }
        }
        $logstr = "INSERT INTO uu_prod_verify(pid,chg_old,cgh_new,`did`,".
            "verified_at,created_at,ctype) VALUES";

        $strOldState = "SELECT apply_limit,id FROM uu_products WHERE id IN({$ids})";
        $this->db->query($strOldState);
        $lists = array();
        $ctype = $status;//产品更新类型1上架，2下架，3涨价，4降价*/
        while($rows = $this->db->fetch_assoc()){
            $lists[] = $rows['id'];
            $chg_old = serialize(array('apply_limit'=>$rows['apply_limit'],'operMsg'=>'修改产品状态'));
            $chg_new = serialize(array('apply_limit'=>$status,'operMsg'=>'修改产品状态'));
            $logstr .= " ({$rows['id']},'{$chg_old}','{$chg_new}','{$operid}',now(),now(),$ctype),";

            //同步数据
            $sync_data[$rows['id']] = array(
                'tbname' =>'uu_products',
                'chg_old'=>array('apply_limit'=>$rows['apply_limit']),
                'chg_new'=>array('apply_limit'=>$status),
            );
        }
        $chgIds = implode(',', $lists);
        $ret = $this->_SetTicketState($status,$p_s,$chgIds);
//        echo $str;
        if($ret['status']=='ok') {
            //是否为同步产品
            $sql = "SELECT id,pid,sync_id,sync_status,apply_did FROM uu_jq_ticket WHERE pid IN(".implode(',',$lists).")";
            $this->db->query($sql);
            while($row=$this->db->fetch_assoc()) {
                if($row['sync_status']!=1) {
                    unset($sync_data[$row['pid']]);
                }
                else {
                    $sync_data[$rows['pid']]['col_id']      = $row['id'];
                    $sync_data[$rows['pid']]['sync_id']     = $row['sync_id'];
                    $sync_data[$rows['pid']]['apply_did']   = $row['apply_did'];
                }
            }
            if (count($sync_data)) {
                $dbArr = \Sync::GetMulDB();
                foreach($sync_data as $pid=>$sd) {
                    \Sync::LogSync('uu_products', $sd['col_id'], $sd['sync_id'],
                        $sd['chg_old'], $sd['chg_new'],$dbArr['trans_le']);
                    \Sync::Notify(array(
                        'action'=>'update_product',
                        'tid'   => $sd['col_id'],
                        'mid'   => $sd['apply_did'],
                    ));
                }
            }
            //同步记录结束

            $logstr = rtrim($logstr,',');
            $this->db->query($logstr);
            return array('status'=>'ok','msg'=>'操作成功！','body'=>$lists);
        }
        return $this->ErrArr;
    }

    /**
     * 设置票类状态[供给范围]
     *
     * @param $status 0未审核1已审核2被拒绝3下架
     * @param $p_s 供给范围
     * @param $chgIds
     * @return array
     */
    private function _SetTicketState($status,$p_s,$chgIds )
    {
        $str = "UPDATE `uu_products` SET `apply_limit`={$status}{$p_s} WHERE id IN (".$chgIds.")";
        if($this->db->query($str)) {
            $ret1 = $this->SyncTicketState($status, $chgIds);
            //echo $ret1;
            $ret2 = array('status'=>'ok','msg'=>'状态更新成功');
            if($ret1!=0) {
                $ret2['body'] = $ret1;
            }
            return $ret2;
        }

    }

    /**
     * 同步产品状态[如果产品有同步到16u先行平台，那么更新状态时需调用此方法]
     *
     * @param $state 状态值
     * @param $id uu_products表id
     * @return int|string
     */
    public function SyncTicketState($state, $id)
    {
        $sql_chk = "SELECT id, sync_id FROM uu_jq_ticket WHERE pid ";
        $sql_chk .= strpos($id, ',')!==false ? "IN($id)" : "=$id";
        $this->db->query($sql_chk);
        $fx_list = array();
        while($r = $this->db->fetch_assoc()) {
            $fx_list[$r['id']] = $r['sync_id'];
        }
        if(!count($fx_list)) {
            return 0;
        }
        //$aes = new \aes('prod_sync');
        $args1 = base64_encode(serialize($fx_list));
        //echo 'arg1=',$args1;
        $token = encrypt($args1, 'sync');
        $ret = request_post('http://www.16u.cc/d/prod_sync.php', array(
            'token' => $token,
            'arg1' => $args1,
            'arg2' => $state
        ));
//        echo $ret;
        return $ret;
    }

    /**
     * 根据门票ID获取门票数据
     *
     * @param integer $tid 门票ID
     * @param integer $apply_did 供应商ID
     * @return mixed
     */
    public function GetTicketById($tid, $apply_did=0) {
        $str = " SELECT t.*,p.p_status,p.apply_limit,p.apply_did as distid ";
        $str .= " FROM uu_jq_ticket t,uu_products p WHERE t.id={$tid}";
        $str .= " AND t.pid=p.id";
        $str .= $apply_did > 0 ? " AND t.apply_did={$apply_did}" : '';
        $str .= " LIMIT 1";
        $this->db->query($str);
        return $this->db->fetch_assoc();
    }

    /**
     * 根据景区ID获取景区名称(uu_land.runtime作为线路的出发地和目的地)
     *
     * @param $id 景区ID
     * @return mixed
     */
    public function GetSceneryTitle($id) {
        //
        $str = "SELECT title,status,p_type,apply_did,runtime,fax,attribute "
            ."FROM uu_land WHERE id={$id}";
        $this->db->query($str);
        $result = $this->db->fetch_assoc();
        return $result;
    }

    public function GetAutoList($keyword, $apply_did = 0)
    {
        $sql = "SELECT id,title FROM uu_land WHERE 1=1";
        if ($apply_did) {
            $sql .= " AND apply_did=$apply_did";
        }
        $sql .= " AND title LIKE %{$$keyword}%";
        $this->db->query($sql);
        $list = array();
        while($row = $this->db->fetch_assoc()) {
            $list[] = $row;
        }
        return $list;
    }

    /**
     * 获取套票产品中的票类数据
     *
     * @param $package_data JSON格式的字符串（参考uu_land表attribute字段）
     * @return array
     */
    public function PackageDataFormat($package_data) {
        $arr = json_decode($package_data, true);
        $package = array();
        $r = array();
        foreach($arr as $p) {
            $package[$p['pid']] = $p['num'];
        }
        $pid_str = implode(',', array_keys($package));
        $str = "SELECT l.id,l.title as ltitle,t.title as ttitle,t.pid,t.delaydays FROM uu_land l"
              . ",uu_jq_ticket t WHERE t.landid=l.id AND t.pid IN({$pid_str})";
        $this->db->query($str);
        while($row=$this->db->fetch_assoc()) {
            $r[] = array(
                'title'=>$row['ltitle'] .'-' .$row['ttitle'],
                'ltitle'=>$row['ltitle'],
                'ttitle'=>$row['ttitle'],
                'pid'=>$row['pid'],
                'lid'=>$row['id'],
                'delaydays'=>$row['delaydays'],
                'num'=>$package[$row['pid']]
            );
        }
        return $r;
    }

    /**
     * 根据ID获取景区数据
     *
     * @param $id 景区表ID
     * @param null $apply_did 供应商ID
     * @return mixed
     */
    public function GetProductById($id,$apply_did=null) {
        $str = "SELECT * FROM `uu_land` WHERE id={$id}"
                . ($apply_did>0 ? " AND apply_did={$apply_did}":"")." LIMIT 1";
        $this->db->query($str);
        return $this->db->fetch_assoc();
    }

    /**
     * 景区状态设置（如果状态不为1，需要更新门票产品的状态为1：禁止销售）
     *
     * @param $id 景区id，数组或数字
     * @param $state 状态
     * @param $oper_name  操作人
     * @return int
     */
    public function SetSceneryState($id,$state,$oper_name=null) {
        $logword = date('Y-m-d H:i:s');
        $stateTxt = array('未审核','在售','下架','删除');
//        if(is_array($id)) {
//            $lid = implode(',',$id);
//        }
//        else {
//            $lid = rtrim($id,',');
//        }
        $lid = intval($id);
        //判定是否为同步产品
        $strOld = "SELECT status,sync_id,sync_status,apply_did FROM uu_land WHERE id={$lid} LIMIT 1";
        $this->db->query($strOld);
        $r          = $this->db->fetch_assoc();
        $old        = $r['status'];
        $sync_id    = $r['sync_id'];
        $sync_status = $r['sync_status'];
        $apply_did  = $r['apply_did'];

        $str = "UPDATE uu_land SET status='{$state}',`passtime`=now() WHERE id={$lid} LIMIT 1";
        //echo $str;
        if($this->db->query($str)) {
            if ($sync_status==1 && $sync_id>0) {
                \Sync::LogSync('uu_land', $lid, $sync_id,array('status'=>$old),array('status'=>$state));
                \Sync::Notify(array(
                    'action'=>'update_land',
                    'lid'=>$lid,
                    'mid'=>$apply_did)
                );
            }

            $logword .= "|ID为[{$lid}]的产品被设置为{$stateTxt[$state]}|操作人:{$oper_name}";
            $pidList = array();
            if($state!=1) {
                $ticketState = 2;//下架
                //删除景区时同时将票类状态设置为删除
                $pstatus = $state==3 ?', p_status=6' : '';
                $strGetTickets = "SELECT id,pid FROM uu_jq_ticket WHERE landid=$lid LIMIT 1";
                //echo $strGetTickets;
                $this->db->query($strGetTickets);
                while($rows = $this->db->fetch_assoc()){
                    $pidList[] = $rows['pid'];
                }
                if(count($pidList)>0) {
                    $pids = implode(',',$pidList);
                    $this->_SetTicketState($ticketState,$pstatus,$pids);
                }
                elseif($state==3){
                    $sql_get_salerid = "SELECT salerid FROM uu_land where id=$lid LIMIT 1";
                    $this->db->query($sql_get_salerid);
                    $data = $this->db->fetch_assoc();

                    $sql_rm = "DELETE FROM uu_land WHERE id=$lid LIMIT 1";
                    $this->db->query($sql_rm);
//                    echo $data['salerid'];
                    $this->_removeRemoteProd($data['salerid']);
//                    echo $ret;
//                    $this->_removeRemoteProd('600004');
                }
            }
            \pft\Log\Log::writeLog($logword, \pft\Log\Log::SYSOPT_LOG_PATH);
            return 1000;
        }
        return 1001;
    }

    /**
     * 设置产品“淘宝绑定”属性
     *
     * @param $landid 景区表的ID
     * @param $flag 0不支持1支持
     * @param $oper_name 操作人姓名
     * @return int
     */
    public function setTaoSupport($landid, $flag,$oper_name)
    {
        $old = "SELECT taobao_support,sync_id,sync_status FROM uu_land WHERE id={$landid} LIMIT 1";
        $this->db->query($old);
        $r = $this->db->fetch_assoc();

        $str = "UPDATE uu_land SET taobao_support={$flag} WHERE id={$landid} LIMIT 1";
        if($this->db->query($str)) {
            if ($r['sync_status']==1 && $r['sync_id']>0) {
                \Sync::LogSync(
                    'uu_land',
                    $landid,
                    $r['sync_id'],
                    array('taobao_support'=>$r['taobao_support']),
                    array('taobao_support'=>$flag)
                );
                \Sync::Notify(array(
                    'action'=>'update_land',
                    'lid'   => $landid,
                    'mid'   => $r['apply_did']
                ));
            }

            $flagTxt = $flag==1?'允许':'禁止';
            $logword = date('Y-m-d H:i:s');
            $logword .= "|ID为[{$landid}]的产品“淘宝绑定”属性被设置为{$flagTxt}|操作人:{$oper_name}";
            \pft\Log\Log::writeLog($logword, \pft\Log\Log::SYSOPT_LOG_PATH);
            return 1;
        }
        else {
            return 0;
        }
    }

    /**
     * 获取所有景区门票列表
     *
     * @param $params
     * @param integer $count
     * @param bool $debug 是否打开调试
     * @return array
     */
    public function GetAllTicketList($params, $count=0,$debug=false) {
        $where = "  WHERE 1=1";
//        $where = "  t.landid=l.id AND t.pid=p.id";
        if(!empty($params['title'])) {
            if( ctype_digit($params['title']) ) {
                if( strlen( $params['title'])==6 ) {
                    $where .= " AND l.salerid={$params['title']}";
                }
                else {
                    $where .= " AND l.id={$params['title']}";
                }
            }
            else {
                $where .= " AND l.`title` LIKE '%{$params['title']}%'";
            }
        }

        if(is_array($params['landid'])) {
            $where .= " AND p.contact_id IN (". implode(',',$params['landid']).")";
        }
        elseif(is_numeric($params['landid'])){
            $where .= " AND p.contact_id={$params['landid']}";
        }
        if(isset($params['salerid'])) {
            $where .= " AND l.salerid='${params['salerid']}'";
        }
        if(is_numeric($params['applyer']) && $params['applyer']>0) {
            $where .= " AND l.apply_did={$params['applyer']}";
        }
        elseif(strpos($params['applyer'], ',')!==false) {
            $where .= " AND l.apply_did IN ({$params['applyer']})";
        }
        if(is_numeric($params['apply_limit'])) {
            $where .= " AND p.apply_limit={$params['apply_limit']}";
        }
        if(is_array($params['status'])) {
            $where .= " AND p.p_status IN(" . implode(',',$params['status']).")";
        }
        elseif($params['status']==-1) {
            $where .= " AND p.p_status<>6";
        }
        elseif($params['status']==0){
            $where .= " AND p.p_status<6 AND p.p_status<>1";
        }
        else {
            $where .= " AND p.p_status='{$params['status']}'";
        }
        if(isset($params['p_type'])) {
            $where .= " AND l.p_type='{$params['p_type']}'";
        }
        if(isset($params['apply_limit'])) {
            $where .= " AND p.apply_limit='{$params['apply_limit']}'";
        }
        if(isset($params['terminal']) && ctype_digit($params['terminal'])) {
            $where .= " AND l.terminal={$params['terminal']}";
        }
        if(isset($params['pids'])) {
            if(is_numeric($params['pids'])) {
                $where .= " AND p.id={$params['pids']}";
            }
            elseif(strpos($params['pids'],',')!==false) {
                $where .= " AND p.id IN({$params['pids']})";
            }
        }
        if($count) {
            $str = "SELECT COUNT(*) AS c FROM uu_jq_ticket t".
                " LEFT JOIN uu_products p ON p.id=t.pid".
                " LEFT JOIN uu_land l ON t.landid=l.id".
                " LEFT JOIN pft_member m ON m.id=t.apply_did".
                $where;
            $this->db->query($str);
            $this->db->fetch_assoc();
            return $this->db->f('c');
        }
//
        else{
            $str = <<<SQL
            SELECT t.id,t.landid,t.title as ticket_title,t.tprice,t.px,t.pay,
            t.storage,t.s_limit_up,t.s_limit_low,t.delaydays,t.ddays,t.getaddr,
            t.buy_limit_up,t.buy_limit_low,t.apply_did,t.pid,l.imgpath,
            l.id,l.title,l.area,l.address,l.jtype,l.addtime,l.terminal,
            l.taobao_support,l.passtime,l.salerid,l.px,l.status,l.topic,
            l.keywords,l.description,l.apply_did,l.p_type,l.attribute,m.dname,
            t.id as ticket_id,p.apply_limit,p.p_status,p.verify_op,p.verify_time
            FROM uu_jq_ticket t
            LEFT JOIN uu_products p ON p.id=t.pid
            LEFT JOIN uu_land l ON t.landid=l.id
            LEFT JOIN pft_member m ON m.id=t.apply_did
            INNER JOIN(
            SELECT p.id FROM uu_products p LEFT JOIN uu_land l
            ON l.id=p.contact_id $where
            LIMIT {$params['limit']},{$params['offset']}) pl
            ON pl.id=t.pid
SQL;
        }
        //排序
        if(isset($params['orderby']) && is_array($params['orderby'])) {
            $tod = "";
            foreach($params['orderby'] as $ord) {
                $tod .= "{$ord['tbl']}.`{$ord['field']}` {$ord['ud']},";
            }
            $str .= ' ORDER BY ' . rtrim($tod,',');
        }

        //$str .= " LIMIT {$params['limit']},{$params['offset']}";
        if($debug) {
            print_r($params);
            echo $str;
        }
        $this->db->query($str);
        $lists = array();
        while($rows = $this->db->fetch_assoc()){
            $lists[] = $rows;
        }
        return $lists;
    }

    /**
     * 获取所有景区门票格式化后的数据列表
     *
     * @param array $params
     * @param integer $count
     * @param \SoapClient $soap
     * @param bool $debug 是否打开调试
     * @return array
     */
    public function GetAllTicketListFormat(array $params, $count=0,
                                           \SoapClient $soap,$debug=false )
    {
        $result = $this->GetAllTicketList($params, $count,$debug);
        if($count) {
            return $result;
        }
        return $this->format($result, $soap);
    }

    /**
     * 获取产品列表
     * @date 2014年9月10日
     * @author Guangpeng Chen
     *
     * @param array $landOption
     * @param array $ticketOption
     * @param bool $onlyLand  是否同时返回票类信息
     * @return array
     */
    public function GetProductsList(Array $landOption, Array $ticketOption=array(), $onlyLand = false)
    {
        $where    = '';
        if(!empty($landOption['supplier'])){
            $where .= " AND l.apply_did={$landOption['supplier']}";
        }
        if (!empty($landOption['title'])) {
            if ( ctype_digit($landOption['title']) ) {
                if( strlen( $landOption['title'])==6 ) {
                    $where .= " AND l.salerid={$landOption['title']}";
                }
                else {
                    $where .= " AND l.id={$landOption['title']}";
                }
            }
            else {
                $where .= " AND l.`title` LIKE '%{$landOption['title']}%'";
            }
        }
        $landIdArr = array();
        if ($landOption['status']===1) {
            $where .= " AND l.status=1";
            //TODO::过滤没有添加过票的景区
            if (isset($landOption['applyer'])) {
                $sqlLidInProducts = "SELECT contact_id FROM uu_products WHERE apply_did={$landOption['applyer']} AND apply_limit=1";
                $this->db->query($sqlLidInProducts);
                while($tmp = $this->db->fetch_assoc() ) {
                    $landIdArr[] = $tmp['contact_id'];
                }
            }
        }
        else {
            //{$landOption['status']}
            $where .= " AND l.status IN(0,1,2)";
            //TODO::仓库中的产品->下架/未审核的票和景区
            if (!empty($landOption['applyer'])) {
                $ticketOption['apply_did']  = $landOption['applyer'];
            }
            $landIdArr = $this->TicketList($ticketOption, true);
        }
        $whereTmp = !empty($landIdArr) ?
            " AND l.id IN(". implode(',', $landIdArr) .")"
            : '';
        if (!empty($landOption['salerid'])) {
            $where .= " AND l.`salerid` = {$landOption['salerid']}";
        }
        if (!empty($landOption['topic'])) {
            $where .= " AND l.`topic` LIKE '%{$landOption['topic']}%'";
        }
        if (isset($landOption['p_type'])) {
            $where .= " AND l.p_type ='{$landOption['p_type']}'";
        }
        if (!empty($landOption['bt']) && !empty($landOption['et'])) {
            $where .= " AND l.`addtime` BETWEEN '{$landOption['bt']}' AND '{$landOption['et']}'";
        }
        if (isset($landOption['applyer'])) {
            $where .= " AND l.apply_did={$landOption['applyer']}";
        }
        if (isset($landOption['terminal']) && ctype_digit($landOption['terminal'])) {
            $where .= " AND l.terminal={$landOption['terminal']}";
        }
        if (isset($landOption['area'])) {
            $where .= " AND area LIKE '{$landOption['area']}_%'";
        }
        $where = $whereTmp . $where;
//        echo $where;
        //TODO::统计总数
        $sqlTotal = "SELECT COUNT(*) AS cnt FROM uu_land l WHERE 1=1 {$where}";
        $this->db->query($sqlTotal);
        $this->db->fetch_assoc();
        $total = $this->db->f('cnt');
        if (!$total) {
            return array('total'=>0);
        }
        //TODO::获取景区数据
        if (isset($landOption['order']) && isset($landOption['by'])) {
            $orderBy = " ORDER BY {$landOption['order']} {$landOption['by']}";
        }
        else {
            $orderBy = " ORDER BY l.id DESC";
        }
        //TODO::分页->根据ID分页
        $sqlPaginate = "SELECT id FROM uu_land l WHERE 1=1 {$where} $orderBy "
                       ." LIMIT {$landOption['limit']},{$landOption['offset']}";
        $this->db->query($sqlPaginate);
        $landIdArr = array();
        while ($tmp=$this->db->fetch_assoc()) {
            $landIdArr[] = $tmp['id'];
        }
        $landIdStr = implode(',', $landIdArr);


        //l.keywords,l.description,l.topic,
        $sql = <<<SQL
        SELECT l.id,l.title,l.area,l.address,l.jtype,l.addtime,l.terminal,
        l.taobao_support,l.passtime,l.salerid,l.px,l.status,l.imgpath,
        l.apply_did,l.p_type,l.attribute
        FROM uu_land l WHERE l.id IN($landIdStr) $orderBy
SQL;
//        if ($_SESSION['account']=='admin') {
//                    echo $sql;
//        }

        $this->db->query($sql);
        $lands = array();
        while( $row = $this->db->fetch_assoc()) {
            $lands[] = $row;
        }
        $ret = array('total'=>$total, 'lands'=>$lands,);
        //TODO:获取票类
        if (!$onlyLand) {
            $ticketOption['landid'] = $landIdArr;
            $ret['tickets']  = $this->TicketList($ticketOption);

        }
        return $ret;
    }

    public function TicketList(Array $option, $onlyLandId=false, $pureTicket=false)
    {
        $where = '1=1';
        if (is_array($option['landid'])) {
            $where .= " AND p.contact_id IN (". implode(',',$option['landid']).")";
        }
        elseif ( strpos($option['landid'], ',')!==false) {
            $where .= " AND p.contact_id IN(".$option['landid'].")";
        }
        elseif (is_numeric($option['landid'])){
            $where .= " AND p.contact_id={$option['landid']}";
        }
        //上架状态
        if (is_numeric($option['apply_limit'])) {
            $where .= " AND p.apply_limit={$option['apply_limit']}";
        }
        //销售范围
        if (is_array($option['status'])) {
            $where .= " AND p.p_status IN(" . implode(',',$option['status']).")";
        }
        elseif ($option['status']==-1) {
            $where .= " AND p.p_status<>6";
        }
        elseif ($option['status']==0){
            $where .= " AND p.p_status<6 AND p.p_status<>1";
        }
        else {
            $where .= " AND p.p_status='{$option['status']}'";
        }
        if(isset($option['pids'])) {
            if(is_numeric($option['pids'])) {
                $where .= " AND p.id={$option['pids']}";
            }
            elseif(strpos($option['pids'],',')!==false) {
                $where .= " AND p.id IN({$option['pids']})";
            }
        }
        if ($option['apply_did']) {
            $where .= " AND p.apply_did={$option['apply_did']}";
        }
        //TODO::只取出景区ID
        if ($onlyLandId) {
            $sql = "SELECT p.contact_id FROM uu_products p WHERE {$where}";
//            echo $sql;
            $this->db->query($sql);
            $landIdArr = array();
            while ($r=$this->db->fetch_assoc()) {
                $landIdArr[] = $r['contact_id'];
            }
            return $landIdArr;
        }
        $sql = <<<SQL
        SELECT t.id,t.landid,t.title,t.tprice,t.px,t.pay,
        t.storage,t.s_limit_up,t.s_limit_low,t.delaydays,t.ddays,t.getaddr,
        t.buy_limit_up,t.buy_limit_low,t.apply_did,t.pid,p.apply_limit,
        p.p_status,p.verify_op,p.verify_time
        FROM uu_products p LEFT JOIN uu_jq_ticket t ON p.id=t.pid
        WHERE $where
SQL;
        $this->db->query($sql);
        $tickets = array();
        $today = date('Y-m-d');
        if ($pureTicket) {
            while( $r=$this->db->fetch_assoc() ) {
                $fprice = $this->soap->get_Dynamic_Price_Merge($r['pid'], $today, 1, '', '', 0);//当日供应价
                $uprice = $this->soap->get_Dynamic_Price_Merge($r['pid'], $today, 1, '', '', 1);//当日零售价
                if($fprice==-1) {
                    $fprice = $this->soap->get_Dynamic_Price_Merge($r['pid'], '', 2, '', '', 0);//最低供应价
                    $uprice = $this->soap->get_Dynamic_Price_Merge($r['pid'], '', 2, '', '', 1);//最低零售价
                }
                $fprice = $fprice>-1 ? $fprice/100 :'已过期';
                $uprice = $uprice>-1 ? $uprice/100 :'已过期';//未配
                $r['fprice']        = $fprice;
                $r['uprice']        = $uprice;
                $tickets[] = $r;
            }
        }
        else {
            while( $r=$this->db->fetch_assoc() ) {
                $fprice = $this->soap->get_Dynamic_Price_Merge($r['pid'], $today, 1, '', '', 0);//当日供应价
                $uprice = $this->soap->get_Dynamic_Price_Merge($r['pid'], $today, 1, '', '', 1);//当日零售价
                if($fprice==-1) {
                    $fprice = $this->soap->get_Dynamic_Price_Merge($r['pid'], '', 2, '', '', 0);//最低供应价
                    $uprice = $this->soap->get_Dynamic_Price_Merge($r['pid'], '', 2, '', '', 1);//最低零售价
                }
                $fprice = $fprice>-1 ? $fprice/100 :'已过期';
                $uprice = $uprice>-1 ? $uprice/100 :'已过期';//未配
                $r['fprice']        = $fprice;
                $r['uprice']        = $uprice;
                $tickets[$r['landid']][] = $r;
            }
        }

        return $tickets;
    }

    /**
     * 获取未添加票类的产品
     *
     * @param int $apply_did 供应商ID
     * @return array
     */
    public function GetEmptyProduct($apply_did=0)
    {
        $sql = "SELECT id,title,jtype,area,terminal,apply_did,salerid,addtime,"
              . "p_type,imgpath FROM uu_land WHERE";
        if($apply_did>0) {
            $sql .= " apply_did=$apply_did AND ";
        }
        $sql .= "id NOT IN (SELECT contact_id FROM uu_products WHERE apply_did=$apply_did)";
        $this->db->query($sql);
        $prods = array();
        while( $r=$this->db->fetch_assoc() ) {
            $prods[] = $r;
        }
        return $prods;
    }

    /**
     * 格式化产品数据（array(产品=>array(票类))）
     *
     * @param $result
     * @param \SoapClient $soap
     * @return array
     */
    public function format($result, \SoapClient $soap)
    {
        $lists = array();
        $tickets = array();
        $today = date('Y-m-d');
        foreach($result as $rows){
            $fprice = $soap->get_Dynamic_Price_Merge($rows['pid'], $today, 1, '', '', 0);//当日供应价
            $uprice = $soap->get_Dynamic_Price_Merge($rows['pid'], $today, 1, '', '', 1);//当日零售价
            if($fprice==-1) {
                $fprice = $soap->get_Dynamic_Price_Merge($rows['pid'], '', 2, '', '', 0);//最低供应价
                $uprice = $soap->get_Dynamic_Price_Merge($rows['pid'], '', 2, '', '', 1);//最低零售价
            }
            $fprice = $fprice>-1 ? $fprice/100 :'未配';
            $uprice = $uprice>-1 ? $uprice/100 :'未配';
            $tickets[$rows['landid']][] = array(
                'id'            => $rows['ticket_id'],
                'title'         => $rows['ticket_title'],
                'tprice'        => $rows['tprice'],
                'px'            => $rows['px'],
                'status'        => $rows['status'],
                'p_status'      => $rows['p_status'],
                'pay'           => $rows['pay'],
                'ddays'         => $rows['ddays'],
                'getaddr'       => $rows['getaddr'],
                'delaydays'     => $rows['delaydays'],
                'storage'       => $rows['storage'],
                's_limit_up'    => $rows['s_limit_up'],
                's_limit_low'   => $rows['s_limit_low'],
                'buy_limit_up'  => $rows['buy_limit_up'],
                'buy_limit_low' => $rows['buy_limit_low'],
//                'open_time'     => $rows['open_time'],
//                'end_time'      => $rows['end_time'],
                'verify_time'   => $rows['verify_time'],
                'pid'           => $rows['pid'],
                'verify_op'     => $rows['verify_op'],
                'fprice'        => $fprice,
                'uprice'        => $uprice,
                'apply_limit'   => $rows['apply_limit'],//审核状态
            );
            $lists[$rows['landid']] = array(
                'id'     => $rows['id'],
                'title'  => $rows['title'],
                'area'  => $rows['area'],
                'jtype'  => $rows['jtype'],
                'addtime'  => $rows['addtime'],
                'address'  => $rows['address'],
                'taobao_support'  => $rows['taobao_support'],
                'salerid'  => $rows['salerid'],
                'px'  => $rows['px'],
                'status'  => $rows['status'],
                'topic'  => $rows['topic'],
                'keywords'  => $rows['keywords'],
                'description'  => $rows['description'],
                'p_type'  => $rows['p_type'],
                'apply_did'  => $rows['apply_did'],
                'terminal' => $rows['terminal'],
                'imgpath'  => $rows['imgpath'],
                'passtime' => $rows['passtime'],
                'dname' => $rows['dname'],
                'tickets'=> $tickets[$rows['id']]
            );
        }
        return $lists;
    }
    /**
     * 获取关联产品
     *
     * @param $lnkid 景区表ID
     * @param bool $format
     * @return array|string
     */
    public function GetLnkProds($lnkid, $format = false) {
        if(empty($lnkid)) {
            return '牵涉的产品ID不能为空！';
        }
        $str = "SELECT title,id FROM uu_land WHERE id IN ($lnkid)";
        $lnkPors = array();
        $this->db->query($str);
        while($rows = $this->db->fetch_assoc()) {
            $lnkPors[$rows['id']] = $rows['title'];
        }
        if($format) {
            return implode(',', $lnkPors);
        }
        return $lnkPors;
    }
}#EOF CLASS